#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
WordMathMerger 插件使用示例
演示如何使用插件进行文档合并
"""

import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

from src.WordMathMerger import WordMathMerger

def example_basic_merge():
    """基础合并示例"""
    print("=== 基础合并示例 ===")
    
    # 获取示例文件路径
    examples_dir = os.path.dirname(__file__)
    
    main_doc = os.path.join(examples_dir, "1.docx")
    docs_to_merge = [
        os.path.join(examples_dir, "2.docx"),
        os.path.join(examples_dir, "3.docx")
    ]
    output = os.path.join(examples_dir, "合并结果_示例.docx")
    
    # 创建合并器
    merger = WordMathMerger()
    merger.verbose = True
    
    # 执行合并
    if os.path.exists(main_doc) and all(os.path.exists(doc) for doc in docs_to_merge):
        result = merger.merge_documents(main_doc, docs_to_merge, output)
        if result:
            print(f"✅ 合并成功！输出文件：{output}")
        else:
            print("❌ 合并失败")
    else:
        print("❌ 示例文件不存在，请确保1.docx, 2.docx, 3.docx在examples文件夹中")

def example_custom_merge():
    """自定义合并示例"""
    print("\n=== 自定义合并示例 ===")
    
    # 让用户选择文件
    examples_dir = os.path.dirname(__file__)
    available_files = [f for f in os.listdir(examples_dir) if f.endswith('.docx')]
    
    if not available_files:
        print("❌ 没有找到.docx文件")
        return
    
    print("可用的文档：")
    for i, file in enumerate(available_files, 1):
        print(f"{i}. {file}")
    
    try:
        main_choice = int(input("选择主文档编号：")) - 1
        merge_choices = input("输入要合并的文档编号（用逗号分隔）：")
        merge_indices = [int(x.strip()) - 1 for x in merge_choices.split(',')]
        
        main_doc = os.path.join(examples_dir, available_files[main_choice])
        docs_to_merge = [os.path.join(examples_dir, available_files[i]) for i in merge_indices]
        output = os.path.join(examples_dir, "自定义合并结果.docx")
        
        merger = WordMathMerger()
        merger.verbose = True
        
        result = merger.merge_documents(main_doc, docs_to_merge, output)
        if result:
            print(f"✅ 自定义合并成功！输出文件：{output}")
        else:
            print("❌ 自定义合并失败")
    except (ValueError, IndexError):
        print("❌ 输入无效")

if __name__ == "__main__":
    print("WordMathMerger 插件使用示例")
    print("=" * 40)
    
    # 检查运行环境
    if not os.path.exists(os.path.join(os.path.dirname(__file__), '..', 'src', 'WordMathMerger.py')):
        print("❌ 插件环境未正确设置")
        sys.exit(1)
    
    # 运行示例
    example_basic_merge()
    
    # 询问是否运行自定义示例
    choice = input("\n是否运行自定义合并示例？(y/n): ")
    if choice.lower() == 'y':
        example_custom_merge()
    
    print("\n示例运行完成！")